<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="getTitle" 
    width="700px" 
    @ok="handleSubmit(true)" 
    showFooter
    destroyOnClose
  >
    <MyAlert type="warning">
      <template #description>
        <div>
          对于配置的参数，一个类型下只能启用一个配置
        </div>
        <div v-if="!record?.canWrite">
          配置不允许当前应用，只能查看
        </div>
      </template>
    </MyAlert>
    <BasicForm @register="registerForm">
      <template #diyForm="{ model, field }">
        <a-button type="link" style="margin-left: -5px;" @click="handleOpenField">去配置</a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { inputFormSchemas } from './data';
  import { BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import * as configTmplApi from '/@/api/infra/configTmpl';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { saveOrUpdateDiyForm } from "/@/api/infra/diyForm"
  import { openWindow } from "/@/utils"
  import MyAlert from "/@/components/My/MyAlert.vue"

  const { createMessage, createConfirm } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const record = ref<any>({});

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 95,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate;
   
      if (unref(isUpdate)) {
        record.value = await configTmplApi.getTmpl({configKey: data.record.configKey}) || {} 
        setDrawerProps({ showOkBtn: record.value.canWrite })
      }
      await initSchema()
      setFieldsValue({ ...record.value })
     
    } finally {
      setDrawerProps({ loading: false})
    }
  });

  const initSchema = async () => {
    const types = await configTmplApi.listConfigType()
    updateSchema([
      {
        field: "type",
        componentProps: ({ formModel, formActionType }) => {
          return {
            optionFilterProp: "label",
            allowClear: true,
            options: types,
          }
        },
      }
    ])

  }

  const getTitle = computed(() => (!unref(isUpdate) ? '新增配置模板' : '编辑配置模板'));

  const handleOpenField = async () => {
    const url = `/onlineDev/formDesigner`
    let values = await validate()
    const diyFormId = values?.diyFormId
    if (!diyFormId || !values?.id) {
      createConfirm({
        iconType: "warning",
        title: "保存提示",
        content: "当前模板尚未保存，确定要保存并创建Diy表单吗？",
        onOk: async () => {
          const dataId = await saveOrUpdateDiyForm(
            {
              id: diyFormId,
              name: `【配置】${values.name}`,
              submitType: 1,
              citations: 1
            },
            diyFormId
          )
          await setFieldsValue({ diyFormId: dataId })
          try {
            await handleSubmit(false)
            openWindow(`${url}?id=${dataId}`)
          } catch (e) {
            await setFieldsValue({ diyFormId: null })
            throw e;
          }
         
        },
        onCancel: () => console.log('已取消'),
      })
    } else {
      openWindow(`${url}?id=${diyFormId}`)
    }
  }

  async function handleSubmit(exit) {
    try {
      let values = await validate();
      if (!values.diyFormId) {
        createMessage.error("请先配置表单字段")
        return
      }
      setDrawerProps({confirmLoading: true});

      const dataId = await configTmplApi.saveOrUpdateTmpl({...values}, unref(isUpdate));
      isUpdate.value = true
      setFieldsValue({ id: dataId })

      exit && closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      exit && emit('success');
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
